
const db = require('db');
const moment = require('moment');
const log = require('tools/log');
const { getTokenInfo } = require('tools/token');
const isLeader = require('tools/isLeader');

module.exports = async ctx => {
    const { connection, run } = db.init();
    try {
        ctx.body = await queryData(ctx, run);
        ctx.body.produceCompletionTime = dateFormat(ctx.body.produceCompletionTime);
        ctx.body.scheduledCompletionTime = dateFormat(ctx.body.scheduledCompletionTime);
        ctx.body.startTime = dateFormat(ctx.body.startTime);
        ctx.body.completionTime = dateFormat(ctx.body.completionTime);
        ctx.body.orderTime = dateFormat(ctx.body.orderTime);
        ctx.status = 200;
    } catch (error) {
        ctx.status = 500;
        ctx.body = error;
        log('---------------------------------------------------');
        console.log(error);
    }
    connection.end();
}

/** 查询数据 */
async function queryData(ctx, run) {
    const { id } = ctx.params;
    const sqlStr = `
        SELECT 
            orders.id,
            orders.company,
            orders.commercialSpecialistId,
            orders.commercialSpecialistName,
            orders.commercialSpecialistEmail,
            orders.pmId,
            orders.pmName,
            orders.pmEmail,
            orders.orderStatus,
            orders.orderTime,
            orders.orderNo,
            orders.deptName,
            orders.deptId,
            orders.clientId,
            orders.project,
            orders.cooperationMode,
            orders.undertakingType,
            orders.details,
            orders.planStartTime,
            orders.startTime,
            orders.scheduledCompletionTime,
            orders.produceCompletionTime,
            orders.completionTime,
            orders.price,
            orders.personDays,
            orders.businessDay,
            orders.amount,
            orders.paymentCycle,
            orders.billingCycle,
            c.clientName
        FROM orders, client as c
        WHERE orders.clientId = c.id
        AND orders.id = ${id}
        ${permission(ctx)}
    `;

    const result = await run(sqlStr);

    if (result.err) {
        throw result.err
    }

    return result.rows[0];
}

/** 数据权限 */
function permission(ctx) {
    const userInfo = getTokenInfo(ctx.header.authorization).userInfo;
    const isL = isLeader(userInfo);

    if (isL) return '';

    return `AND (orders.commercialSpecialistId=${userInfo.userid} OR orders.pmId=${userInfo.userid})`
}

/** 时间格式转换 */
function dateFormat(date) {
    const r = date ? moment(date).format('YYYY-MM-DD') : undefined;
    return r === 'Invalid date' ? undefined : r;
}